using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Object = UnityEngine.Object;

namespace LFromeWork
{
    public class GameObjectPoolEntity
    {
        /// <summary>
        /// 加载出来的asset Prefab
        /// </summary>
        private GameObject Prefab;

        /// <summary>
        /// 实例列表
        /// </summary>
        private LinkedList<GameObject> InstanceList = new LinkedList<GameObject>();
        
        /// <summary>
        /// 获取名字
        /// </summary>
        /// <returns></returns>
        public string GetPrefabName()
        {
            return Prefab.name;
        }

        /// <summary>
        /// 出池子
        /// </summary>
        /// <param name="namePath"></param>
        /// <param name="instanceComplete"></param>
        public GameObject Spawn(string assetFullName,Transform parent = null)
        {
            GameObject obj = null;
            if (Prefab != null)
            {
                if (InstanceList.First == null)
                    obj = GameObject.Instantiate(Prefab);
                else
                    obj = InstanceList.First.Value;
            }
            else
            {
                AssetRefEntity assetEntity = GameLaunch.Resources.AssetLoader.GetExitAssetRefEntity(assetFullName);
                if (assetEntity == null)
                    GameLaunch.LogError("请先加载Asset或者等待Asset加载完成再调用Spawn path :: " + assetFullName);
                else
                {
                    Prefab = assetEntity.Target as GameObject;
                    obj = GameObject.Instantiate(Prefab);
                }
            }
            obj.transform.SetParent(parent);
            obj.SetActive(true);
            return obj;
        }
        
        /// <summary>
        /// 回池
        /// </summary>
        /// <param name="namePath"></param>
        /// <param name="instanceComplete"></param>
        public void Despawn(GameObject obj)
        {
            if (obj == null)
                return;
            InstanceList.AddLast(obj);
            obj.transform.SetParent(GameLaunch.Instance.PoolParent);
            obj.SetActive(false);
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Release()
        {
            DestroyInstance();
            Prefab = null;
        }
        
        /// <summary>
        /// 销毁实例化的 物体
        /// </summary>
        private void DestroyInstance()
        {
            LinkedListNode<GameObject> currLoad = InstanceList.First;
            while (currLoad != null)
            {
                if (currLoad.Value != null)
                {
                    GameObject.Destroy(currLoad.Value);
                    currLoad.Value = null;
                }
                currLoad = currLoad.Next;
            }
            InstanceList.Clear();
        }
        
    }
}
